package com.tw.academy.basic.$7_long_method;

/**
 * This class is a example for bad smell;
 *
 * @author  Thoughtworks
 * @version 1.0
 * @since   2018-1-1
 */
public class OrderReceipt {
    private Order order;

    private static final String HEADER = "======Printing Orders======\n";
    private static final String SPACE = "\t";
    private static final String SALES_TAX = "Sales Tax";
    private static final String TOTAL_AMOUNT = "Total Amount";
    private static final String LINE_ENDER = "\n";
    private static final Double TAX_RATE = 0.1;


    public OrderReceipt(Order order) {
        this.order = order;
    }

    public String printReceipt() {
        StringBuilder receipt = new StringBuilder();
        appendHeader(receipt, HEADER);
        appendUserInfo(receipt);

        double totalSaleTax = 0d;
        double totalAmount = 0d;
        for (LineItem lineItem : order.getLineItems()) {
            appendItemDetail(receipt, lineItem);

            double salesTax = lineItem.totalAmount() * TAX_RATE;
            totalSaleTax += salesTax;
            totalAmount += lineItem.totalAmount() + salesTax;
        }

        appendTaxInfo(receipt, totalSaleTax);
        appendTotalAmount(receipt, totalAmount);
        return receipt.toString();
    }

    private void appendTotalAmount(StringBuilder receipt, double totalAmount) {
        receipt.append(TOTAL_AMOUNT).append(SPACE).append(totalAmount);
    }

    private void appendTaxInfo(StringBuilder receipt, double totalSaleTax) {
        receipt.append(SALES_TAX).append(SPACE).append(totalSaleTax);
    }

    private void appendUserInfo(StringBuilder receipt) {
        receipt.append(order.getCustomerName());
        receipt.append(order.getCustomerAddress());
    }

    private void appendHeader(StringBuilder receipt, String header) {
        receipt.append(header);
    }

    private void appendItemDetail(StringBuilder receipt, LineItem lineItem) {
        receipt.append(lineItem.getDescription());
        receipt.append(SPACE);
        receipt.append(lineItem.getPrice());
        receipt.append(SPACE);
        receipt.append(lineItem.getQuantity());
        receipt.append(SPACE);
        receipt.append(lineItem.totalAmount());
        receipt.append(LINE_ENDER);
    }
}